<template>
  <div class="dictionaryData h100">
    <div class="PageContent">
      <el-row style="text-align: left;line-height: 5em;">
        <el-button type="primary" plain v-if="btnRight.btnCrematorMngAdd" @click="addCremator()" >添加</el-button>
        <el-button type="primary"  v-if="btnRight.btnCrematorMngEdit" @click="modifyCremator()">修改</el-button>
        <el-button type="danger"  v-if="btnRight.btnCrematorMngDelete" @click="deleteCremator()">删除</el-button>
      </el-row>
      <el-table
        ref="singleCrematorTable" :header-cell-style="{background:'rgb(246,247,251)',color:'#606266'}"
        :data="crematorTableData"
        stripe
        border
        @row-click="handleRowClick"
        @select="select" @select-all="selectAll"
        style="width: 100%;height: calc(100% - 110px);overflow-y: scroll">
        <el-table-column
          type="selection"
          width="55">
        </el-table-column>
        <el-table-column
          property="furnaceCode"
          label="火化炉编码"
          align = 'center'
          width="200">
        </el-table-column>
        <el-table-column
          property="furnaceType"
          label="火化炉类型"
          align = 'center'
          width="200">
        </el-table-column>
        <el-table-column
          align = 'center'
          label="禁用状态"
          width="150" >
          <template slot-scope="{row,$index}">
            <span v-if="row.disableState==0">有效可用</span>
            <span v-else-if="row.disableState==1">无效禁用</span>
            <span v-else-if="row.disableState==3">维修</span>
          </template>
        </el-table-column>
        <el-table-column
          property="sort"
          align = 'center'
          label="排序"
          width="150">
        </el-table-column>
        <el-table-column
          property="itemUnit"
          align = 'center'
          label="规则说明"
          min-width="500">
          <template slot-scope="{row,$index}" >
            <div v-if="row.ruleItems" v-for="(item, index) in row.ruleItems" :key="index">
              <p style="width: 100%;white-space: pre-wrap;">
                <span>用途:【{{ item.purpose }}】单价:【{{ item.itemPrice }}】{{ item.ruleType }}{{ item.ruleDescribe }}</span>
              </p>
            </div>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <el-dialog title="火化炉信息维护" :visible.sync="dialogCrematorVisibleType" width="700px" v-dialogDrag   border  @close="closeDialog()">
      <el-form :model="saveFormData" :rules="rules" ref="crematorDialog" :inline="true" label-width="120px" :disabled="saveFlag">
        <el-row :gutter="5">
          <el-form-item label="火化炉编码:" prop="furnaceCode" >
            <el-input v-model="saveFormData.furnaceCode"  maxlength="50"></el-input>
          </el-form-item>
        </el-row>
        <el-row>
          <el-form-item label="火化炉类型:" prop="furnaceTypeCode">
            <el-select v-model="saveFormData.furnaceTypeCode" @change="TypeChange(saveFormData.furnaceTypeCode)" style="width: 185px;" placeholder="请选择"  :maxlength="50">
              <el-option
                v-for="item in furnaceType"
                :label="item.dataText"
                :value="item.dataCode"/>
            </el-select>
          </el-form-item>
        </el-row>
        <el-row :gutter="5">

          <!--<el-select v-model="saveFormData.ruleDescribe" style="width: 185px;" placeholder="请选择"  :maxlength="50">-->
          <!--<el-option-->
          <!--v-for="item in ruleItems"-->
          <!--:label="item.dataText"-->
          <!--:value="item.dataCode"/>-->
          <!--</el-select>-->
          <el-form-item label="收费规则:">
            <div v-if="saveFormData.furnaceTypeCode" class="ruleItem">
              <p class="content" v-for="(item, index) in showRule" :key="index">
                <span>用途:【{{ item.purpose }}】</span>，
                <span>单价:【{{ item.itemPrice }}】</span>，
                <span>{{ item.ruleType }}</span>，
                <span>{{ item.ruleDescribe }}</span>
              </p>
            </div>
          </el-form-item>
        </el-row>
        <el-row :gutter="5">
          <el-form-item label="状态:" prop="disableState" >
            <el-select v-model="saveFormData.disableState" onkeydown="return (event.keyCode!=8)" style="width: 185px;" placeholder="请选择"  :maxlength="50">
              <el-option
                v-for="item in disableState"
                :label="item.label"
                :value="item.value"/>
            </el-select>
          </el-form-item>
        </el-row>
        <el-row :gutter="5">
          <el-form-item label="描述:"  >
            <el-input  type="textarea" v-model="saveFormData.furnaceDescribe" style="width: 495px;"></el-input>
          </el-form-item>
        </el-row>
        <el-row :gutter="5">
          <el-form-item label="备注:"  >
            <el-input  type="textarea" v-model="saveFormData.remark" style="width: 495px;"></el-input>
          </el-form-item>
        </el-row>
        <el-row>
          <el-form-item label="排序:"  >
            <el-input  v-model="saveFormData.sort" onkeyup="value= (value.match(/^\d*(\.?\d{0,2})/g)[0]) || null" maxlength="11"></el-input>
          </el-form-item>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer" style="text-align: right;">
        <el-button type="primary" v-if="btnRight.btnCrematorMngSave" @click="submit()"  :disabled="saveFlag">保存</el-button>
        <el-button  type="primary" plain  v-if="btnRight.btnCrematorMngCancel" @click="cancelForm()">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
  import * as API from '@/api/systemApplication'
  import {treeDictionaryformate} from "../../utils/treeDictionaryformate";
  export default {
    name: "dictionaryData",
    data(){
      return{
        rules: {
          furnaceCode: [
            {required: true, message: '请填写', trigger: 'blur'},
          ],
          furnaceTypeCode: [
            {required: true, message: '请选择', trigger: 'change'},
          ],
          disableState: [
            {required: true, message: '请选择', trigger: 'change'},
          ],
        },
        creamatorTreeData: [{
          label: '火化炉管理',
          children: [],
        }],
          crematorTableData:[],
        defaultProps: {
          children: 'children',
          label: 'label'
        },
        tableData: [{
          "id": 0,//主键
          "furnaceTypeCode":"",//火化炉类型编码
          "furnaceCode":"",//火化炉编码
          "furnaceDescribe":"",//火化炉描述
          "furnaceState":"",//火化炉状态
          "disableState":"",//禁用状态
          "sort": 0,
          "remark": "string",//备注
          "version": 0,
          "funeralParlourCode":"",//殡仪馆代码
          "ruleDescribe":""//收费规则描述

        }],
        currentRow: null,
        tableSelection:[],
        selectOrg: {
          orgsid: []
        },
        showRule:[],
        saveFlag:false, //保存标志
        onpresscTime:0,  //  阻止短时间内连续点击
        dialogCrematorVisibleType:false,  //项目分类维护对话框
        saveFormData:{       //保存火化炉信息
          "id": 0,//主键
          "furnaceTypeCode":"",//火化炉类型编码
          "furnaceCode":"",//火化炉编码
          "furnaceDescribe":"",//火化炉描述
          "furnaceState":"",//火化炉状态
          "disableState":0,//禁用状态
          "sort": 0,
          "remark": "",//备注
          "version": 0,
          "funeralParlourCode":"",//殡仪馆代码，
          "ruleDescribe":""//收费规则描述
        },
        furnaceType:[],
        disableState: [
          {label: "有效可用", value: 0}, {label: "无效禁用", value: 1}, {label: "维修", value: 3}
        ],
        ruleItems:[],//收费规则
        btnRight: {
          btnCrematorMngAdd: true, //添加
          btnCrematorMngEdit: true,//修改
          btnCrematorMngDelete: true,//删除
          btnCrematorMngSave: true,//保存
          btnCrematorMngCancel: true,//取消
        }

      }
    },

    mounted(){
      //载入火化炉信息树
      this.loadCrematorList();
      //获得菜单按钮
      this.btnRight = this.$route.meta.buttons;
      //遍历属性赋值将true与false字符串转换成布尔型的值
      for (let key of Object.keys(this.btnRight)) {
        this.btnRight[key]=(this.btnRight[key]|| this.btnRight[key]=="true")?true:false;
      }
    },
    methods: {
      //类型改变后加载规则
      TypeChange(id){
        this.showRule = []
        if (id && this.ruleItems && this.ruleItems.length) {
          this.ruleItems.forEach(item=>{
            if (item.dataCode == id) {
              this.showRule.push(item)
            }
          })
        }
      },
      //字典基本信息
      loadCrematorList(){
        let postData={
        }
        API['loadFurnaceList'](postData).then(response=>{
          const { data }=response;
          if (!data) {
            this.$message('数据读取失败')
            return
          }
          this.crematorTableData = data
        }).catch(error => {
          this.$message(error)
        })
      },changeSort(val){
        val = val.replace(/(^\s*)|(\s*$)/g, "")
        if(!val) {
          this.saveFormData.sort= "";
          return
        }
        let reg = /[^\d]/g
        // 只能是数字和小数点，不能是其他输入
        val = val.replace(reg, "")
        if (val.length>10)
          val=val.slice(0,10)
        this.saveFormData.sort = val;
      },

      addCremator() {
          //alert(123);
        this.saveFormData={       //保存火化炉信息
          "id": 0,//主键
            "furnaceTypeCode":"",//火化炉类型编码
            "furnaceCode":"",//火化炉编码
            "furnaceDescribe":"",//火化炉描述
            "furnaceState":"",//火化炉状态
            "disableState":0,//禁用状态
            "sort": 0,
            "remark": "",//备注
            "version": 0,
            "funeralParlourCode":"",//殡仪馆代码，
            "ruleDescribe":""//收费规则描述
        }
        //传送数据
        let postData={
          "id": 0,
          "dictTypeCodes": [
            "furnace_type"
          ]
        }
        let this_add=this;
        //载入字典明细
        API['loadFurnaceWithId'](postData).then(response=>{
          let data =response;
          if (!data) {
            this.$message(data.message)
            return
          }else{
            //载入数据
            //火化炉类型
            let furnace_type=data.data.dicts.furnace_type;
            //收费规则
            let ruleItems=data.data.ruleItems;
            this_add.furnaceType=furnace_type;
            // this_add.saveFormData={id:0};
            this_add.ruleItems=ruleItems;
            this_add.showRule = []
            this_add.dialogCrematorVisibleType = true;
            //加载data
          }

        }).catch(error => {
          this.$message(error)
        })

      },
      //明细修改
      modifyCremator(){
        let data= this.$refs.singleCrematorTable.selection;
        let item=null;
        let this_modify=this;
        if(data && data.length>0){
          item=data[0];
        }else{
          this.$message("未选中")
          return ;
        }
        let postData={
          "id": item.id,
          "dictTypeCodes": [
            "furnace_type"
          ]
        }
        //载入字典明细
        API['loadFurnaceWithId'](postData).then(response=>{

          let data =response;
          if (!data) {
            this.$message(data.message)
            return
          }else{
            //载入数据
            //火化炉类型
            let furnace_type=data.data.dicts.furnace_type;
            //收费规则
            this.ruleItems=data.data.ruleItems;
            this_modify.saveFormData=data.data.furnace;
            /*初始化收费规则*/
            this.showRule = []
            if (this.saveFormData.furnaceTypeCode && this.ruleItems && this.ruleItems.length) {
              this.ruleItems.forEach(item=>{
                if (item.dataCode == this.saveFormData.furnaceTypeCode) {
                  this.showRule.push(item)
                }
              })
            }
            this.loadCrematorList()
            this_modify.dialogCrematorVisibleType = true;

            //加载data
            this_modify.furnaceType=furnace_type;
          }

        }).catch(error => {

          // this.$message(error)
        })
      },
      formatterRuleItems: function(row, column, cellValue) {
        let data=cellValue;
        if( data && data.length && data.length>0){
          let itemStr="";
          for(var i=0;i<data.length;i++){
            itemStr+=data[i].ruleDescribe;
          }
          return itemStr;
        }else{
          return "暂无";
        }

      },
      closeDialog(){
        this.saveCremator={};
        this.dialogCrematorVisibleType=false;
      },//根据明细id删除明细数据
      deleteCremator(){
        let data= this.$refs.singleCrematorTable.selection;
        let item=null;
        if(data && data.length>0){
          item=data[0];
        }else{
          this.$message("未选中")
          return ;
        }
        this.$confirm('删除信息, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          let postData=[{
            "id": item.id,
            "version":item.version
          }]
          //载入字典明细
          API['deleteFurnaceWithId'](postData).then(response=>{
            let data=response;
            if (!data) {
              this.$message(data.message)
              return
            }else{
              this.$message(data.message)
              this.loadCrematorList()
            }
            //加载data

          }).catch(error => {
            // this.$message(error)
          })
        }).catch(() => {
          //几点取消的提示
        });

      } ,
      //加载字典类型
      R(){
        let postData={
        }
        //this.treeData = treeDictionaryformate(this.ceshi)
        API['loadFurnaceList'](postData).then(response=>{

          const { data }=response;
          if (!data) {
            this.$message('数据读取失败')
            return
          }

          this.creamatorTreeData = this.treeCrematorFormat(data)

        }).catch(error => {
          // this.$message(error)
        })
      },
      //根据id加载物品，服务类型详情
      loadServiceWithId(dictCode){
        let postData={
          "dictCode": dictCode
        }
        let this_load=this;
        API['loadServiceWithId'](postData).then(response=>{
          const { data }=response;
          if (!data) {
            this_load.$message('数据读取失败')
            return
          }
          let loadData= this_load.treeCrematorFormat(data);
          //获得第一个返回值的children
          this_load.crematorTableData = loadData[0].children;
        }).catch(error => {
          this_load.$message(error)
        })
      },//数据格式为树形
      treeCrematorFormat(data){
        let result=[{
          label: '系统字典',
          children: []
        }]
        if (data && data.length){
          data.forEach(item=>{
            if (item.furnaceCode) {
              item.label = item.remark
              item.id = item.furnaceCode
            }
          })
          result[0].children = data
        }
        return result

      },
      //tree单选
      handleCheck(data,checked, node){

        this.$refs.crematorTree.setCheckedNodes([data]);
        node = this.$refs.crematorTree.getCheckedNodes();
        console.log(node[0].furnaceCode);
        // this.editArr = [data.furnaceCode];
        let this_local=this;
        //描述
        this_local.saveCremator.dataDescribe=data.furnaceCode;
        //类型编码，记录字典编码code
        this_local.saveCremator.dictCode=data.furnaceCode;
        //加载字典明细项
        this_local.loadServiceWithId(data.furnaceCode);
      },
      //点击行触发，选中或不选中复选框
      handleRowClick(row, column, event) {
        if (this.$refs.singleCrematorTable.selection.length>0){
          this.$refs.singleCrematorTable.toggleRowSelection(this.tableSelection[0],false);
        }
        this.$refs.singleCrematorTable.toggleRowSelection(row);
        this.tableSelection = [row]
      },
      select(selection, row) {
        // 选择项大于1时
        if (selection.length > 1) {
          let del_row = selection.shift();
          // console.log('把数组的第一个元素从其中删除后', selection);
          this.$refs.singleCrematorTable.toggleRowSelection(del_row, false); // 用于多选表格，切换某一行的选中状态，如果使用了第二个参数，则是设置这一行选中与否（selected 为 true 则选中）
        }
        this.tableSelection = selection
      },

      selectAll(selection) {
        if (selection.length >1) {
          selection.length = 1;
        }
        this.tableSelection = selection
      },
      //火化炉保存
      submit(){
        if ((Date.now() - this.onpresscTime) > 2000) {
          this.onpresscTime = Date.now()
          console.log(Date.now())
        }else{
          return
        }
        this.$refs.crematorDialog.validate(valid=>{
          if (valid) {
            this.saveFlag = true;
            let postData=this.saveFormData;
            let this_submit=this;
            API['saveFurnace'](postData).then(response=>{
              if(response){
                let data=response;
                if (!data) {
                  this.saveFlag = false;
                  this.$message('数据保存失败')
                  return
                }
                this_submit.dialogCrematorVisibleType=false;
                this.loadCrematorList()
                this.saveFlag = false;
              }else{
                this.$message('数据保存失败')
                this.saveFlag = false;
              }

            }).catch(error => {
              // this.$message(error)
            })
          }
        })

      },//取消
      cancelForm(){
        this.saveCremator={};
        this.dialogCrematorVisibleType = false
      },//验证整数
      onlySortNumber(){
        // 先把非数字的都替换掉，除了数字和.
        let obj=this.saveFormData.sort;
        obj=Number.parseInt(obj);
        this.saveFormData.sort=obj;
      }

    },
    watch:{
      "dialogCrematorVisibleType"(){
        if (this.dialogCrematorVisibleType==false){
          this.$nextTick(() => {
            this.$refs.crematorDialog.resetFields();
          })
        }

      }
    }
  }
</script>
<style scoped>

</style>
